package net.wanho.hospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.wanho.hospital.exception.PasswordErrorException;
import net.wanho.hospital.po.Patient;
import net.wanho.hospital.mapper.PatientUserMapper;
import net.wanho.hospital.service.PatientUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.wanho.hospital.util.JwtUtil;
import net.wanho.hospital.vo.PatientVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 汤小洋
 * @since 2023-12-27
 */
@Service
public class PatientUserServiceImpl extends ServiceImpl<PatientUserMapper, Patient> implements PatientUserService {

   /**
    *   按查询分页查询
    */
    @Override
    public IPage<Patient> findPage(int pageNum, int pageSize, Patient patient) {
        QueryWrapper<Patient> wrapper = null;
        IPage<Patient> page = new Page<>(pageNum, pageSize);
        page = this.page(page, wrapper);
        return page;
    }

    @Override
    public Map<String,Object> findPatientPage(int pageNumber, int size, String query) {
        // 分页
        IPage<Patient> page = new Page<>(pageNumber, size);

        // 查询条件
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Patient::getPName, query)
                .orderByDesc(Patient::getPId);

        // 查询
        this.page(page, wrapper);

        // 封装结果
        Map<String,Object> map = new HashMap<>();
        map.put("patients", page.getRecords());
        map.put("total", page.getTotal());

        return map;
    }

    @Override
    public PatientVo login(int pId, String pPassword) {
        Patient patient = this.getById(pId);

        // 判断用户是否存在

        // 判断密码是否正确
        if(! patient.getPPassword().equals(DigestUtils.md5DigestAsHex(pPassword.getBytes()))){
            throw new PasswordErrorException("密码不正确！");
        }

        // 封装结果
        Map<String,Object> payload = new HashMap<>();
        payload.put("pId", patient.getPId());
        payload.put("pName", patient.getPName());
        payload.put("pCard",patient.getPCard());
        String token = JwtUtil.generate(payload);

        PatientVo patientVo = new PatientVo();
        patientVo.setPId(patient.getPId());
        patientVo.setPName(patient.getPName());
        patientVo.setToken(token);

        return patientVo;
    }

}
